package com.roadmap.client.msg;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import com.roadmap.client.module.BaseManager;
import com.roadmap.common.BaseEntity;
import com.roadmap.common.RdcConst;
import com.roadmap.common.RdcLogger;
import com.roadmap.common.BaseEnum.ActionType;
import com.roadmap.entities.Comment;
import com.roadmap.exception.ActionNotSupportedException;
import com.roadmap.exception.EntityNotFoundException;
import com.roadmap.exception.InvalidActionException;
import com.roadmap.exception.InvalidQueryException;
import com.roadmap.exception.InvalidStatusException;
import com.roadmap.exception.InvalidValueException;
import com.roadmap.exception.NullObjectException;
import com.roadmap.exception.ServerException;
import com.roadmap.repo.db.RdcQuery;

public class CommentManager extends BaseManager {
	private final static Logger _log = RdcLogger
			.getLogger(CommentManager.class);

	public CommentManager(String aspirantId) {
		super(aspirantId, Comment.class);
	}

	public CommentManager(String aspirantId, BaseEntity parent) {
		super(aspirantId, Comment.class, parent);
	}

	@Override
	public void create(BaseEntity entity) throws NullObjectException,
			InvalidActionException, InvalidValueException, ServerException,
			EntityNotFoundException, ActionNotSupportedException,
			InvalidStatusException {
		if (!checkEntityIsValid(entity)) {
			return;
		}

		getDbUtil().save(entity);
		// find out the entry which the comment is added to, and add a notice
		// record for this entry
		Comment cmt = (Comment) entity;
		Class clazz = RdcConst.getEntityNameClazz(cmt.getEntryType());
		// 如果用户评论自己的item将不会有通知
		if (clazz != null && !cmt.getAuthorId().equals(cmt.getHostId())) {
			BaseEntity entry = getDbUtil()
					.getEntityById(clazz, cmt.getTypeId());
			// 对比entry的所有者ID和评论的host ID，如果两者不匹配，说明该评论是回复
			getNoticeManager().notifyForEntry(entry, ActionType.COMMENT,
					cmt.getHostId());
		}
	}

	@Override
	public List getEntitiesOfParent() throws NullObjectException,
			InvalidQueryException, ServerException, InvalidValueException {
		String sql = "select {c.*}, a.realName from comment as c, aspirant as a where typeId=:tid and c.authorId=a.aspirantId order by updatedTime ASC";
		RdcQuery query = this.getDbUtil().createNativeSQLQuery(sql);
		query.addEntity("c", this.getManagedEntityType());
		query.setParameter("tid", this.getParent().getId());
		query.addScalar("realName");
		List comments = null;
		List results = query.getResults();
		if (results != null && !results.isEmpty()) {
			comments = new ArrayList();
			Iterator iter = results.iterator();
			while (iter.hasNext()) {
				Object[] result = (Object[]) iter.next();
				Comment cmt = (Comment) result[0];
				cmt.setAuthorName((String) result[1]);
				comments.add(cmt);
			}
		}
		return comments;
	}
}
